import schedule from "node-schedule";
import fs from "fs";
import path from "path";
import { getDateBefore } from "./date.js";
import { exec } from "child_process";

let jobs = [];
const clearLoggers = () => {
  jobs.push(schedule.scheduleJob("10 * * * * *", () => {}));
};

let scheduleList = {
  clearLoggers,
};

export const StartSchedule = () => {
  for (let key in scheduleList) {
    scheduleList[key]();
  }
};

export const deleteLogs = (day = 3) => {
  fs.readdir(
    path.join(process.cwd() + "/server/logger/logs/"),
    function (err, files) {
      try {
        if (files.length) {
          files.forEach((f) => {
            let _date = f.match(/\-([\s\S]*?)\./g);
            if (!_date) return;
            let date = _date[0].replace(/-/g, "").replace(/\.$/, "");
            // 清空日志
            let clearDate = getDateBefore(new Date(), day, "YYYYMMDD");
            if (clearDate > date) {
              exec(
                `rm -rf ${path.join(
                  process.cwd() + "/server/logger/logs/" + f
                )}`,
                (err, stdout, stderr) => {
                  if (err) throw err;
                  console.log("file/folder deleted");
                }
              );
            }
          });
        }
      } catch (err) {
        console.log(err);
      }
    }
  );
};
